package org.alala.user.util.app;

import java.io.IOException;

import org.alala.user.util.error.GeneralExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public abstract class SpringApp {

	private static Logger logger = LoggerFactory.getLogger(SpringApp.class);
	private GeneralExceptionHandler errorHandler = new GeneralExceptionHandler();
	
	protected ApplicationContext context;
	
	public SpringApp initWithPaths(String... paths) {
		if(paths.length == 0) {
			return initDefault();
		}
		context = new ClassPathXmlApplicationContext(paths);
		return this;
	}
	
	public SpringApp initWithNames(String dir, String... fileNames) {
		if(fileNames.length == 0) {
			return initDefault();
		}
		String[] paths = new String[fileNames.length];
		for(int i = 0; i < fileNames.length; i++) {
			paths[i] = String.format("classpath:%s/%s.xml", dir, fileNames[i]);
		}
		context = new ClassPathXmlApplicationContext(paths);
		return this;
	}
	
	public <T> T getBean(Class<T> clz) {
		return context.getBean(clz);
	}
	
	public SpringApp initDefault() {
		context = new ClassPathXmlApplicationContext("classpath:spring/*.xml");
		return this;
	}
	
	protected boolean isWait() {
		return true;
	}
	
	
	public void start() {
		
		if(context == null) {
			this.initDefault();
		}
		
		//设置全局异常捕获
		Thread.currentThread().setUncaughtExceptionHandler(errorHandler);
		
		String name = this.getClass().getSimpleName();
		
		logger.info(name + " starts ok.");
		
		if(isWait()) {
			try {
				System.in.read();
			} catch (IOException e) {
				logger.error("suspend using in.read() failed");
			}
		}
	}
}
